package com.xs.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.xs.domain.Admin;
import com.xs.service.AdminService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author 徐双
 * @ClassName TokenUtils
 * @date 2022-11-28 17:08
 * @Description:
 * @Version:1.0
 */

@Component
public class TokenUtils {

    private static AdminService staticAdminService;
    @Resource
    private  AdminService adminService;

    @PostConstruct
    private void setSysUserService() {
        staticAdminService=adminService;
    }

    /**
     * 生成token
     * @param userId
     * @param sign
     * @return
     */
    public static String genToken(String userId,String sign){
        return JWT.create().withAudience(userId)//将userid保存到token；里面，作为载荷
        .withExpiresAt(DateUtil.offsetHour(new Date(),2))//2小时后token过期
        .sign(Algorithm.HMAC256(sign));//以password作为token的密钥
    }

    /**
     * 获取当前登录的用户信息，通过token
     * @return
     */
    public static Admin getCurrentUser(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isBlank(token)){
                String userId = JWT.decode(token).getAudience().get(0);
                return staticAdminService.getById(Integer.valueOf(userId));
            }
        }catch (Exception e) {
            return null;
        }
        return null;
    }















}
